﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace Webserver
{
    class Connection
    {
        private string url;
        public string message { get; set; }
        Socket socket;

        public Connection(string _url)
        {
            this.url = _url;
        }

        // Setup the socket connection and send the request
        public bool Connect()
        {
            try
            {
                IPAddress[] host = Dns.GetHostAddresses(url);
                socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                socket.Connect(host, 80);
            }
            catch (SocketException e)
            {
                Console.WriteLine("{0} Error code: {1}.", e.Message, e.ErrorCode);
                return false;
            }
            return true;
        }
        
        // Use the Send and Receive methods on socket to send and receive data
        public void Close()
        {    
            socket.Close();
            socket.Dispose();
        }

        // Displays sending with a connected socket
        // using the overload that takes a buffer.
        public int SendReceiveTest()
        {
            //byte[] msg = Encoding.UTF8.GetBytes(message);

            byte[] msg = Encoding.ASCII.GetBytes(message);

            byte[] bytes = new byte[2048];

            try
            {
                // Blocks until send returns.
                int i = socket.Send(msg);
                Console.WriteLine("Sent {0} bytes.", i);

                // Get reply from the server.
                i = socket.Receive(bytes);
                Console.WriteLine(Encoding.UTF8.GetString(bytes));
            }
            catch (SocketException e)
            {
                Console.WriteLine("{0} Error code: {1}.", e.Message, e.ErrorCode);
                return (e.ErrorCode);
            }
            return 0;
        }

    }
}
